package com.demo.controller;

import com.demo.model.User;
import com.demo.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.rmi.server.InactiveGroupException;

import javax.annotation.Resource;
import java.util.*;

@RestController
public class UserController {

    @Resource
    UserService userService;

    /**
     * 新增数据示例
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/add")
    private String getUserById(String username,String password){
        User user = new User();
        user.setUserName(username);
        user.setPwd(password);
        user.setCreateTime(new Date());
        userService.addUser(user);
        return "success";
    }

    /**
     * 根据id删除数据
     *
     * @param userId
     * @return
     */
    @RequestMapping("/delete")
    private String deleteUserById(String userId){
        Integer id = Integer.parseInt(userId);
        userService.deleteUserById(id);
        return "success";
    }


    /**
     * 修改用户数据的时候必须知道用户的id
     *
     * @param id
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/update")
    private String updateUser(String id, String username,String password){
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setUserName(username);
        user.setPwd(password);
        user.setUpdateTime(new Date());
        userService.updateUser(user);
        return "success";
    }


    /**
     * 根据id删除数据
     *
     * @param userId
     * @return
     */
    @RequestMapping("/getUserList")
    private String getUsersById(String userId){
        String[] idsStr = userId.split(",");
        List<Integer> ids = new ArrayList<>();
        for(String str : idsStr){
            ids.add(Integer.parseInt(str));
        }
        List<User> users = userService.getUsersById(ids);
        return users.toString();
    }
}
